const express = require('express');
const router = express.Router();
const { PrismaClient } = require('@prisma/client')
const prisma = new PrismaClient()
const upload = require('../multer/multer')
const { generateToken, parseToken } = require('../utils/token')
const { returnUserData, returnMyColumnsData, returnMemberData, returnMyAtricals } = require('../utils/prismaData');
const { generateColumnId } = require('../utils/uuid')
const { sendMail } = require('../mail/mailer');
const { mailCode } = require('../utils/codeGenerate');
/* GET users listing. */
// 获取个人id的专栏数据 + member
router.get('/data', upload.none(), async (req, res) => {
    const token = req.headers.authorization.split(' ')[1]
    const tokenData = await parseToken(token)
    if (!tokenData) return res.status(401).send({ msg: '登录过期' })
    const { id } = tokenData
    const { userId } = req.query
    if (id !== userId) return res.status(403).send({ msg: '用户信息错误' })
    const columnData = await prisma.column.findMany({
        where: {
            createId: id
        },
        select: {
            id: true,
            name: true,
            mainPath: true,
            description: true,
            createId: true
        }
    }).finally(async () => await prisma.$disconnect())
    if (columnData === null) return res.status(404).send({ msg: '无信息记录' })
    // 包装返回值
    res.status(200).send(returnMyColumnsData(columnData))
})

// 获取指定id专栏下的member
router.get('/member', upload.none(), async (req, res) => {
    const token = req.headers.authorization.split(' ')[1]
    const tokenData = await parseToken(token)
    if (!tokenData) return res.status(401).send({ msg: '登录过期' })
    const { id } = tokenData
    const { columnId } = req.query
    if (columnId === '') return res.status(401).send({ msg: '错误的专栏信息' })
    const memberData = await prisma.column.findUnique({
        where: {
            id: columnId
        },
        select: {
            member: {
                select: {
                    user: {
                        select: {
                            id: true,
                            img: true,
                            name: true
                        }
                    }
                }
            }
        }
    }).finally(async () => await prisma.$disconnect())
    if (memberData === null) return res.status(404).send({ msg: '无相关信息' })
    // 包装成员数据
    res.status(200).send(returnMemberData(memberData))
})

// 获取我的文章
router.get('/myArticles', upload.none(), async (req, res) => {
    const token = req.headers.authorization.split(' ')[1]
    const tokenData = await parseToken(token)
    if (!tokenData) return res.status(401).send({ msg: '登录过期' })
    const { id } = tokenData
    const { userId } = req.query
    if (userId !== id) return res.status(401).send({ msg: '错误的用户信息' })
    const articlesData = await prisma.article.findMany({
        where: {
            authorId: id
        },
        select: {
            id: true,
            published: true,
            title: true,
            createAt: true,
            content: true,
            mainImg: true,
        }
    })
    if (articlesData === null) return res.status(404).send({ msg: '无相关数据' })
    // 数据包装
    res.status(200).send(returnMyAtricals(articlesData))
})

// 改个人信息
router.post('/info', upload.single('userImg'), async (req, res) => {
    const token = req.headers.authorization.split(' ')[1]
    const tokenData = await parseToken(token)
    if (!tokenData) return res.status(401).send({ msg: '登录过期' })
    const { id } = tokenData
    if (!req.body.username && req.body.username !== undefined) {
        // 不能为空串
        return res.status(403).send({ msg: '不能为空串' })
    }
    const { username, gender, tel, address, bio, prefer } = req.body
    let filePath = undefined
    const { file } = req
    
    if (file !== undefined) {
        filePath = file.path.replace(/public\\/, '').replace(/\\/g, '/')
    }
    const updateResult = await prisma.user.update({
        where: {
            id: id
        },
        data: {
            name: username,
            img: filePath,
            gender,
            tel,
            address,
            bio,
            prefer
        }
    })
    if (updateResult === null) {
        return res.status(403).send({ msg: '修改失败' })
    }
    res.status(200).send(returnUserData(updateResult))
});

// sendEmail
router.post('/mail', upload.none(), async (req, res) => {
    const token = req.headers.authorization.split(' ')[1]
    const tokenData = await parseToken(token)
    if (!tokenData) return res.status(401).send({ msg: '登录过期' })
    const { id } = tokenData
    const { email } = req.body
    const subject = '验证邮箱'
    const code = mailCode()
    const text = `【百味阁】验证码 ${code} 用于百味阁邮箱信息绑定，3分钟有效，请勿泄露或转发。`
    sendMail(email, subject, text)
    //   存储到数据库
    const codeData = await prisma.user.update({
        where: {
            id: id
        },
        data: {
            verifiCode: code
        }
    })
    if (codeData === null) res.status(401).send({msg: '发生了错误'})
    // 定时后删除
    res.status(200).send(`已发送邮件到${email}`)
})

// 验证绑定
router.post('/verify', upload.none(), async (req, res) => {
    const token = req.headers.authorization.split(' ')[1]
    const tokenData = await parseToken(token)
    if (!tokenData) return res.status(401).send({ msg: '登录过期' })
    const { id } = tokenData
    const { email, userCode } = req.body;
    // 假设你已经将用户的邮箱和发送给用户的验证码存储在数据库中
    // 这里需要从数据库中获取用户的验证码
    const dbCode = await prisma.user.findUnique({
        where: {
            id: id
        },
        select: {
            verifiCode: true
        }
    })
    if (dbCode === null) res.status(401).send({msg: '发生了错误'})
    if (userCode !== dbCode.verifiCode) res.status(400).send({ msg: '错误的验证码' });
    // 验证码正确，可以进行下一步操作
    const mailData = await prisma.user.update({
        where: {
            id
        },
        select: {
            email: email
        }
    })
    if (mailData === null) res.status(401).send({msg: '发生了错误'})
    res.status(200).send({ msg: '绑定成功' });
});

// 改专栏信息 + 创建新专栏
router.post('/update', upload.single('columnImg'), async (req, res) => {
    const token = req.headers.authorization.split(' ')[1]
    const tokenData = await parseToken(token)
    if (!tokenData) return res.status(401).send({ msg: '登录过期' })
    const { id } = tokenData
    const { columnId, columnName, columnMsg } = req.body
    if (req.file.path) {
        filePath = req.file.path.replace(/public\\/g, '')
    }
    console.log(columnId, 198);
    if (columnId === '' || 'undefined') {
        console.log('创建');
        // 创建
        const newColumnId = generateColumnId()
        await prisma.$transaction([
            prisma.column.create({
                data: {
                    id: newColumnId,
                    createId: id,
                    name: columnName,
                    mainPath: filePath,
                    description: columnMsg,
                },

            }),
            prisma.member.create({
                data: {
                    columnId: newColumnId,
                    memberId: id
                }
            })
        ]).then((result) => {
            res.status(200).send(result[0])
        }).catch((err) => {
            res.status(403).send({ msg: '创建失败' });
        }).finally(async () => {
            await prisma.$disconnect();
        })
    } else {
        // 更新数据
        const columnData = await prisma.column.findUnique({
            where: {
                id: columnId
            }
        })
        if (columnData === null) return res.status(404).send({ msg: '错误的专栏信息' })
        const columnUpdata = await prisma.column.update({
            where: {
                id: columnId
            },
            data: {
                name: columnName,
                mainPath: filePath,
                description: columnMsg,
            },
        }).finally(async () => await prisma.$disconnect())
        if (columnUpdata === null) return res.status(404).send({ msg: '更新错误' })
        res.status(200).send(columnUpdata)
    }
})




module.exports = router;
